package cn.edu.hdu;

import java.util.Random;
import java.util.Vector;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;

public class GameView extends SurfaceView implements Callback, Runnable{
	public static int screen_height, screen_width;
	
	private Thread thread;
	private SurfaceHolder holder;
	private Paint paint;
	private Canvas canvas;
	private Vector<Circle> circles;
	private Random ran;
	//http://www.himigame.com/android-game/346.html
	private boolean flag;

	public GameView(Context context) {
		super(context);
		this.setKeepScreenOn(true);
		circles = new Vector<Circle>();
		ran = new Random();
		holder = this.getHolder();
		holder.addCallback(this);
		paint = new Paint();
		paint.setAntiAlias(true);
		this.setFocusable(true);
	}
	

	public void run() {
		while(flag){
			logic();
			draw();
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	public void draw(){
		try{
			canvas = holder.lockCanvas();
			canvas.drawColor(Color.BLACK);
			if(circles != null){
				for(int i=0;i<circles.size();i++){
					circles.elementAt(i).draw(canvas, paint);
				}
			}
		}catch(Exception e1){
			// TODO: handle exception
		} finally {
			try{
				if(canvas != null){
					holder.unlockCanvasAndPost(canvas);
				}
			}catch(Exception e2){}
		}
	}

	public void surfaceCreated(SurfaceHolder holder) {
		screen_width = this.getWidth();
		screen_height = this.getHeight();
		flag = true;
		thread = new Thread(this);
		thread.start();
	}
	
	private void logic(){
		if(circles != null){
			for(int i=0;i<circles.size();i++){
				circles.elementAt(i).logic();
			}
		}
	}

	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		Log.v("ball", "surfaceChanged");
	}

	public void surfaceDestroyed(SurfaceHolder holder) {
		flag = false;
	}


	@Override
	public boolean onTouchEvent(MotionEvent event) {
		circles.addElement(new Circle((int)event.getX(), (int)event.getY(), ran.nextInt(this.getWidth()/10)));
		return super.onTouchEvent(event);
	}

}
